# 用户账号相关的功能
# 注册 登录 短信 注销
from django.http.response import JsonResponse
from django.shortcuts import render, redirect, HttpResponse
# redis
from django.shortcuts import HttpResponse
# 腾讯云短信
from web.Forms import account
from web import models
# 验证码
from utils.image_code import check_code
from io import BytesIO
import uuid
import datetime

'''
前端渲染标签---前端获取数据---发送后端----后端校验---错误渲染/正确保存数据库
'''


# 注册
def register(request):
    dic = {
        'status': 1,
        'msg': ''
    }
    if request.method == 'GET':
        form = account.register_form()
        return render(request, 'register.html', locals())
    # print(request.POST)
    # 通过注册校验
    form = account.register_form(data=request.POST)
    if form.is_valid():
        # instance = form.save()  instance 当前创建的对象
        # 价格策
        policy_obj = models.PricePolicy.objects.filter(category=1, title='v0').first()
        # 保存数据
        instance = form.save()
        # 创建交易记录
        models.Transact.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=policy_obj,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now()
        )
        return JsonResponse(dic)
    dic['status'] = 0
    dic['msg'] = form.errors
    return JsonResponse(dic)


# 手机号发送
def SendSms(request):
    dic = {
        'status': 1,
        'msg': ''
    }
    form = account.sms_form(request, data=request.GET)
    if form.is_valid():
        return JsonResponse(dic)
    dic['status'] = 0
    dic['msg'] = form.errors
    return JsonResponse(dic)


# 短信登录
def login_sms(request):
    dic = {
        'status': 1,
        'msg': ''
    }
    if request.method == 'GET':
        form = account.login_sms_form()
        return render(request, 'login_sms.html', locals())
    form = account.login_sms_form(data=request.POST)
    if form.is_valid():
        mobile_phone = form.cleaned_data.get('mobile_phone')
        # user_object 一定存在 手机号只有存在才能登录
        user_object = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
        # 存放session表中 在后端session表中，在浏览器上也是一个字符串
        request.session['user_id'] = user_object.id
        # request.session['user_name'] = user_object.username
        request.session.set_expiry(60 * 60 * 24 * 14)

        return JsonResponse(dic)
    dic['status'] = 0
    dic['msg'] = form.errors
    return JsonResponse(dic)


# 用户登录
def login(request):
    if request.method == 'GET':
        form = account.login_form(request)
        return render(request, 'login.html', {'form': form})
    form = account.login_form(request, data=request.POST)
    if form.is_valid():
        # 存放session表中 在后端session表中，在浏览器上也是一个字符串
        # 在django——session里面找不到，但是确实存在
        # print(request.session.get('user_id'))
        return redirect('home')
    return render(request, 'login.html', locals())


# 注销登录
def login_out(request):
    request.session.flush()
    return redirect('home')


# 验证码
def image_code(request):
    """ 生成图片验证码 """

    image_object, code = check_code()

    request.session['image_code'] = code
    request.session.set_expiry(60)  # 主动修改session的过期时间为60s

    stream = BytesIO()
    image_object.save(stream, 'png')
    return HttpResponse(stream.getvalue())
